System Design Interview Crash Course
Rate this course
Ask Author
Contribute
Back to course home

74% completed

Vote For New Content
Introduction
Course Overview
Who this Course Is for
How to Cover the Lessons
Day 1: Content Delivery & Media
Design YouTube
Design Netflix
Day 2: Key-Value & Caching Internals
Design a Distributed Cache (like Redis)
Design a Key-Value Store (like DynamoDB)
Day 3: Chat & Real-time Communication
Design WhatsApp
Design Discord
Day 4: Reliability & Observability
Design a Distributed Rate Limiter
Design a Metrics & Monitoring System (like Datadog/Prometheus)
Day 5: Storage & Retrieval (Blob & File)
Design Amazon S3
Design Google Ads
Day 6: E-Commerce & Transactions
Design Amazon Shopping Cart
Design Stripe Payment Gateway
Design Stock Exchange
Day 7: Social Graph & Networking
Design Facebook “People You May Know”
Design LinkedIn Connections
Design Twitter Timeline
Day 8: Collaboration Tools
Design a Collaborative Whiteboard (Miro)
Design Google Docs
Day 9: Streaming & Big Data
Design an Ad Click Aggregator
Design a Live Comment Streaming Service (Twitch Chat)
Day 10: Software Infrastructure
Design a Code Deployment System
Design an API Gateway
Day 11: Distributed Compute & Intelligence
Design Amazon Lambda
Design ChatGPT
Design Typeahead/Autocomplete
Design Google Search
Design AirBnB
Design Uber/Lyft
Design a Distributed Lock Manager (like Chubby)
Design a Distributed Job Scheduler (like Cron)
Final Words
Design Amazon Lambda
Image

Here is the step-by-step system design for Amazon Lambda (Function-as-a-Service).

1. Problem Definition and Scope

We are designing a multi-tenant Function-as-a-Service (FaaS) platform.

The system allows developers to upload code (functions) and executes it on demand without the user managing any infrastructure.

The platform handles provisioning, patching, scaling, and security isolation.

  • Users: Developers (uploading code) and Event Sources (API Gateway, S3, SQS, Cron).

  • Main Actions: Uploading code, invoking functions (synchronously or asynchronously), and viewing logs.

  • Scope:

    • Control Plane: Function management (CRUD) and code storage.
    • Data Plane: Scheduling and executing code securely at scale.
    • Out of Scope: Billing, Lambda@Edge, and complex VPC networking internals.
Image

2. Clarify functional requirements

Must Have:

  • Function Management: Users can upload code (zip) and configure runtime (Python, Node, etc.), memory, and timeout.

  • Synchronous Invocation: Support Request/Response pattern (client waits for result).

  • Asynchronous Invocation: Support Event pattern (fire-and-forget).

  • Auto-scaling: Automatically scale from 0 to thousands of concurrent instances based on traffic.

  • Isolation: Strict security boundaries; one user's code must not access another's memory or data.

  • Logging: Capture stdout/stderr from the function execution.

Nice to Have:

  • Versioning: Support for $LATEST and immutable numbered versions.

  • Dead Letter Queues (DLQ): Handling events that fail to process after retries.

Image

3. Clarify non-functional requirements

  • Scale: Support 10 billion invocations per day.

  • Throughput:

    • Average QPS: ~115,000 requests per second.
    • Peak QPS: ~600,000 requests per second (highly bursty).
  • Latency:

    • Warm Start: < 20ms overhead (reusing an existing environment).
    • Cold Start: < 500ms overhead (downloading code + booting environment).
  • Availability: 99.99% for the invocation API.

  • Durability: 11 nines for stored code artifacts.

  • Isolation: Must use hardware-level virtualization (MicroVMs) rather than simple container namespaces for security.

Image

4. Back of the envelope estimates

  • Traffic (QPS):
    • 10^10 reqs/day / 86,400 sec ≈ 115,000 QPS.
    • Peak factor 5x ≈ 600,000 QPS.
  • Storage (Code):
    • Assume 2 million active functions.
    • Average code size: 30 MB (compressed).
    • Total Storage: 2 x 10^6 x 30 MB = 60 TB. (Trivial for S3).
  • Bandwidth (Internal):
    • If 1% of peak traffic is a "Cold Start" (requiring code download):
    • 6,000 cold starts/sec x 30 MB = 180 GB/sec.
    • Constraint: We need aggressive caching of code on worker nodes to avoid saturating the network from S3.
Image

5. API design

We will use a REST API split into Management and Invocation.

1. Create Function

  • POST /v1/functions
  • Body: {"name": "resize", "runtime": "python3.9", "memory": 128, "handler": "main.py", "code_url": "s3://..."}
  • Response: 201 Created with metadata.

2. Invoke Function (Sync)

  • POST /v1/functions/{name}/invocations
  • Header: X-Invocation-Type: RequestResponse
  • Body: JSON payload.
  • Response: 200 OK {"status": "success", "payload": ...}

3. Invoke Function (Async)

  • POST /v1/functions/{name}/invocations
  • Header: X-Invocation-Type: Event
  • Response: 202 Accepted (Request queued).

4. Update Configuration

  • PUT /v1/functions/{name}/config
  • Body: {"env_vars": {"DB_HOST": "..."}}

6. High level architecture

We separate the system into the Control Plane (Management) and Data Plane (Execution).

Components:

  1. Function Manager: Handles CRUD operations. Uploads code to S3 and metadata to DB.

  2. Frontend Invoker: The entry point for invocations. Stateless. Validates auth and asks the Placement Service for a worker slot.

  3. Worker Manager (Placement): The "Brain". Tracks the capacity of all Worker Nodes and assigns function executions.

  4. Worker Fleet: Physical servers managed by us.

  5. MicroVM: The secure isolation unit (e.g., Firecracker) running the user's code.

  6. Event Queue: Buffers asynchronous requests to smooth out traffic spikes.

Image

7. Data model

We need a database optimized for high-throughput key-value reads (looking up function config by name).

Database: NoSQL (e.g., DynamoDB).

  • Table: Functions
  • Partition Key: account_id
  • Sort Key: function_name
  • Attributes: runtime, handler, memory_mb, s3_bucket, s3_key, env_vars (encrypted).

Storage (S3):

  • Stores the immutable .zip code artifacts.
  • Path: code/{account_id}/{function_name}/{version_hash}.zip.

8. Core flows end to end

To understand how a FaaS platform operates at scale, we must trace the life of a request through the system.

We will explore four distinct flows: Deployment (getting code into the system), Cold Starts (provisioning new resources), Warm Starts (reusing resources), and Asynchronous Events (background processing).

Flow 1: Code Deployment (Control Plane)

Scenario: A developer uploads a new version of their function code via the CLI or Console.

Before code can run, it must be securely stored and indexed. This flow emphasizes durability and security.

  1. Request: The developer sends a POST /functions request with the function metadata (name, runtime, memory).

  2. Presigned URL (Optimization): The Function Manager validates the request but does not accept the file upload directly (to avoid blocking the API with large binary transfers). Instead, it generates and returns a temporary S3 Presigned URL.

  3. Direct Upload: The client uploads the .zip file directly to the S3 Blob Store using the secure URL.

  4. Metadata Persistence: Once the upload is confirmed, the Function Manager updates the DynamoDB table with the S3 path, version number, and configuration.

  5. Propagation: The function is now "live." Note that we do not push code to Worker Nodes yet. Code is pulled "Just-In-Time" (lazy loading) during invocation to save fleet storage.

Image

Flow 2: Synchronous Invocation – The "Cold Start"

Scenario: A user invokes a function that hasn't run recently, or the system is scaling up. There are no active containers ready.

This is the most "expensive" path in a FaaS system. The goal is to go from "zero" to "running code" as securely as possible.

  1. Ingestion: The Frontend Invoker receives the request, authenticates the user, and fetches the function’s metadata (S3 path, memory) from its local cache or DynamoDB.
  2. Placement (The Decision):
  • The Invoker asks the Placement Service: "I need a slot for Function A with 128MB RAM."
  • The Placement Service checks its state. It sees no idle (warm) containers available.
  • It selects a healthy Worker Node with available capacity and returns the assignment.
  1. Worker Provisioning (The Heavy Lift): The chosen Worker Node performs these steps sequentially:
  • Download: Checks the local disk cache for the code .zip. If missing, downloads it from S3.
  • Sandboxing: Starts a Firecracker MicroVM. Unlike a container (Docker), this MicroVM has its own kernel, providing hardware-level isolation for security.
  • Initialization: Boots the language runtime (e.g., Python Interpreter) and runs the user's global initialization code (imports, variable setup).
  1. Execution: The Worker passes the event payload to the handler function. The code runs, and the response is returned to the client.
  2. The "Freeze" (Crucial Optimization):
  • Crucially, the Worker does not kill the MicroVM immediately.
  • It pauses (freezes) the process in memory. The CPU usage drops to zero, but the memory state is preserved.
  • The slot is marked as "Warm" and ready for the next request.

Latency Impact: Steps 3 & 4 create the "Cold Start" latency (typically 200ms – 1s).

Image

Flow 3: Synchronous Invocation – The "Warm Start"

Scenario: The user invokes the function again shortly after the first request.

This is the "Happy Path" (95%+ of traffic). The system skips the heavy lifting by reusing the frozen environment.

  1. Placement Lookup: The Frontend Invoker queries the Placement Service.

  2. Smart Routing: The Placement Service sees an entry in its state: "Worker Node #42 has a frozen MicroVM for Function A."

  3. Direct Routing: The request is routed directly to Worker Node #42.

  4. The "Thaw":

  • The Worker receives the request.
  • It unfreezes the existing MicroVM. (No S3 download, no OS boot, no Python init).
  • The code executes immediately.
  1. Latency: Because the environment was ready, overhead is < 20ms.
Image

Flow 4: Asynchronous Invocation (Event-Driven)

Scenario: An S3 upload triggers a function (e.g., "Resize Image"). The client does not wait for the result.

This flow prioritizes reliability and buffering over immediate speed.

  1. Ingestion: The client sends the request with header X-Invocation-Type: Event.

  2. Queueing: The Frontend Invoker pushes the event into an internal Message Queue (e.g., Kafka/SQS) and immediately returns 202 Accepted to the client. The client connection closes.

  3. The Poller: A separate Poller Service reads messages from the queue. It acts as an internal client, triggering Flow 2 (Cold) or Flow 3 (Warm) to process the event.

  4. Reliability (Retries):

  • If the function fails (crashes/timeouts), the Poller does not delete the message.
  • It retries with Exponential Backoff (wait 1s, 2s, 4s...).
  • If retries are exhausted (e.g., 3 times), the message is moved to a Dead Letter Queue (DLQ) for manual inspection.
Image

9. Caching and read performance

Performance in FaaS depends entirely on minimizing "Cold Starts."

  1. Metadata Cache:
    • Frontend Invokers cache function config (memory, handler) in local memory (TTL 60s). This avoids hitting the DB for every request.
  2. Code Cache (Worker Layer):
    • Worker Nodes maintain an LRU cache of unzipped code folders on their local NVMe SSDs.
    • Most "Cold Starts" are actually just "VM Boots" using locally cached code, avoiding the slow S3 download.
  3. Execution Context Cache (The Warm Pool):
    • The system keeps MicroVMs alive for ~10-15 minutes after execution.
    • Sticky Routing: The Scheduler tries to route requests for Function A to the same node to maximize cache hits.

10. Storage, indexing and media

  • Primary Data: DynamoDB for metadata.

  • Blob Storage: S3 for code artifacts.

    • Optimization: Use "Tiered Layer Caching." Common base layers (e.g., standard Python library) are pre-baked into the base MicroVM image on all workers to reduce download size.
  • Logs:

    • Functions write to stdout/stderr.
    • A Log Agent (sidecar) on the Worker Node captures these streams.
    • The agent pushes logs asynchronously to a centralized store (e.g., CloudWatch Logs).
    • Design Note: Logging is fire-and-forget; the function execution does not wait for log persistence.

11. Scaling strategies

1. Scaling the Worker Manager (The Bottleneck):

  • A centralized scheduler cannot handle 600k QPS.
  • Solution: Decentralized Placement / Partitioning.
    • Shard the Worker Manager by FunctionID.
    • "Power of Two Choices": The Frontend Invoker queries 2 random Worker Managers and picks the one with the shortest queue. This removes the single central bottleneck.

2. Scaling Worker Nodes:

  • Monitor fleet-wide CPU/Memory utilization.
  • If utilization > 70%, the Auto-Scaling Group provisions more physical servers (EC2 instances).

3. Thundering Herd (User Scaling):

  • If a user scales from 0 to 10k concurrent requests instantly, we cannot spin up 10k VMs in 1 second.
  • Token Bucket: Enforce concurrency limits per account (e.g., 1,000 concurrent).
  • Throttling: Return 429 Too Many Requests if the user exceeds their quota.

12. Reliability, failure handling and backpressure

1. Isolation (MicroVMs):

  • We use Firecracker MicroVMs (KVM-based).
  • Unlike Docker, MicroVMs have their own kernel. If a user exploits a kernel bug, they are contained within their VM and cannot access the host or other users.

2. Fault Tolerance:

  • Worker Death: If a physical server fails, the Worker Manager updates its map. In-flight requests fail (client retries); new requests route to healthy nodes.
  • Availability Zones: Deploy Worker Fleet across 3 AZs.

3. Backpressure:

  • The internal Async Queue acts as a buffer.
  • If the queue fills up, the API Gateway starts rejecting Async requests (503 Service Unavailable) to protect the downstream system.

13. Security, privacy and abuse

Security:

  • Sandboxing: MicroVMs are the primary defense against "Noisy Neighbors" and data leaks.
  • Network: Functions run in a restricted network namespace. They cannot see other MicroVMs.
  • Permissions: Functions execute with temporary IAM credentials injected as environment variables.

Abuse Prevention:

  • Crypto Mining: Detect patterns of 100% CPU usage for max duration consistently.
  • Fork Bombs: Limit the number of processes (PIDs) a MicroVM can spawn.

14. Bottlenecks and next steps

Bottlenecks:

  • Cold Start Latency: Even with optimizations, booting a heavy runtime (Java/Spring) takes seconds.
  • Placement Latency: Finding the right node at 600k QPS is computationally expensive.

Next Steps:

  • SnapStart: Initialize the VM, take a memory snapshot, and save it to disk. For new invocations, restore from the memory snapshot instead of booting. This reduces Java cold starts from 5s to 200ms.
  • Provisioned Concurrency: Allow premium users to pay to keep instances warm 24/7, bypassing the cold start logic entirely.

Summary

  1. Architecture: Distinct Control Plane (Metadata) and Data Plane (Execution).

  2. Isolation: Used Firecracker MicroVMs for hardware-level security.

  3. Performance: Optimized via Warm Starts (freezing VMs) and Code Caching on workers.

  4. Scale: Solved scheduling bottlenecks using Sharded/Decentralized Placement.

Design an API Gateway
Design ChatGPT
Mark as Completed

On this page

1. Problem Definition and Scope

  1. Clarify functional requirements
  1. Clarify non-functional requirements

4. Back of the envelope estimates

5. API design

6. High level architecture

7. Data model

8. Core flows end to end

Flow 1: Code Deployment (Control Plane)

Flow 2: Synchronous Invocation – The "Cold Start"

Flow 3: Synchronous Invocation – The "Warm Start"

Flow 4: Asynchronous Invocation (Event-Driven)

9. Caching and read performance

10. Storage, indexing and media

11. Scaling strategies

12. Reliability, failure handling and backpressure

13. Security, privacy and abuse

14. Bottlenecks and next steps

Summary